<html>
<head>
<#assign basePath=request.contextPath>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>后台管理系统</title>
<#include "/WEB-INF/views/template/bootMainCss.ftl" parse=true encoding="utf-8">
    <link href="${basePath}/bootstrap/css/font-awesome.min.css" rel="stylesheet">
    <link href="${basePath}/bootstrap/css/form.lzy.css" rel="stylesheet">
    <link href="${basePath}/bootstrap/css/good.lzy.css" rel="stylesheet">
    <link href="${basePath}/bootstrap/plugin/bootstrap-datetimepicker/bootstrap-datetimepicker.min.css"
          rel="stylesheet">
    <style>
        .name{ float: right;}
        .row{ margin: 0;}
        .shop-img{ text-align: left; padding-left: 30px;}
        .shop-img img{ margin-right: 10px;}
        .panel-body{ padding-bottom:15px; }
        #tbodyId{ font-size: 13px;}
        #myTable thead{ font-size: 14px;}
        h1 {
            display: block;
            margin-bottom: 20px;
            border-bottom: 1px solid #999;
            font-size: 16px;
            padding-left: 2px;
            font-weight: bold;
            line-height: 35px;
        }
    </style>
</head>
<body>

<div class="panel panel-f5">
    <input type="hidden" id="id" name="id" <#if dto??>value="${dto.id!}"</#if>/>
    <div class="panel panel-lzy">
        <div class="panel-body row">
            <h1>● 代言人信息</h1>
            <input type="hidden" id="_ctx" value="${basePath}"/>
            <input type="hidden" id="id" name="id"/>
            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4  detail-span">&nbsp;姓名：<#if dto??>value="${dto.name!}"</#if></span>
            </div>
            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4  detail-span">&nbsp;手机号：<#if dto??>value="${dto.name!}"</#if></span>
            </div>
            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4  detail-span">&nbsp;成为代言人时间：<#if dto??>value="${dto.name!}"</#if></span>
            </div>
        </div>
    </div>
</div>
<!-- 分页查询的地址-->
<div class="panel-body panel-white">
    <div class="table-responsive">
        <h1>● 下属代理商</h1>
        <div class="panel panel-f5">
            <div class="panel-heading row">
                <input type="hidden" id="managerId" name="managerId" value="">
                <span class="btn btn-primary" id="selectManager">绑定</span>
                <button type="button" class="btn btn-primary" onclick="batchDown();">批量解除</button>
            </div>
        </div>
        <table id="myTable"
               class="table table-hover"
               data-url="${basePath}/admin/product/classify/json"
               data-pageSize="10,50,100" data-method="GET">
            <thead>
            <!-- 需要循环的字段  对应mapper文件-->
            <tr>
                <th  data-type="checkbox" data-field="id"></th>
                <th  data-field="id">序号</th>
                <th  data-field="phone" data-call="true">代言人手机</th>
                <th  data-field="name" width="15%">姓名</th>
                <th  data-field="createTime" data-call="true" width="25%">所在地</th>
                <th  data-field="createTime" data-call="true">成为代理商时间</th>
                <th  data-field="button" data-call="true">操作</th>
            </tr>
            </thead>
            <tbody id="tbodyId">
            </tbody>
        </table>

    </div>
</div>
<div class="form-group">
    <span class="control-label col-sm-4 col-xs-4"></span>
    <div class="col-sm-8 col-xs-8">
        <button type="button" class="btn btn-success" onclick="submitForm();" style="margin-top: 15px; margin-right: 30px;"><i class="fa fa-check"></i> 提交</button>
    </div>
</div>

<!--代理商列表-->
<div class="super-bg">
    <div class="super-box">
        <form id="Form" class="form-horizontal" method="post">
            <h3>选择代理商<i class="fa fa-close"></i></h3>
            <div class="super-tit">
                <input class="text" type="text" name="key" value="" placeholder="请输入手机号或姓名">
                <input class="submit" type="submit" value="搜索" onclick="reSearch(1)">
                <button type="button" class="btn btn-success" onclick="submitForm1();><i class="fa fa-check"></i> 确定</button>
            </div>
            <div class="panel-body panel-white">
                <div class="table-responsive">
                    <table width="95%" border="0" align="center"
                           id="myTable"
                           class="table table-hover"
                           data-url="/admin/member/json"
                           data-pageSize="10,50,100" data-method="GET">
                        <thead>
                        <tr>
                            <th width="10%">ID</th>
                            <th width="25%">代理商姓名</th>
                            <th width="25%">代理商手机</th>
                            <th width="15%">操作</th>
                        </tr>
                        </thead>
                        <tbody id="layTable">

                        </tbody>
                    </table>
                </div>
                <div class="row">
                    <div align="left" class="col-xs-4">
                        <div class="input-group">
                            <span class="input-group-addon" id="pageCount"></span> <select
                                id="pageSize" onchange="reSearch(1)" class="form-control"
                                style="width: 100px"></select>
                        </div>
                    </div>
                    <div align="right" class="col-xs-8">
                        <ul class="pagination" id="pagination"></ul>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="good-add-suc">
    <span>
        <b>操作成功</b>
        该页面将在 5 秒后自动跳转！
        <a href="/admin/identity" target="_parent">返回列表</a>
    </span>
</div>

<#include "/WEB-INF/views/template/bootMainJs.ftl" parse=true encoding="utf-8">
<script type="text/javascript" src="${basePath}/bootstrap/js/utils.js" type="text/javascript"></script>
<script type="text/javascript" src="${basePath}/bootstrap/plugin/jqPaginator/jqPaginator.js"></script>
<script type="text/javascript" src="${basePath}/bootstrap/plugin/jqPaginator/myPage.js"></script>
<script type="text/javascript">
    //循环列表数据以及操作按钮
    //    function tableCallBack(data, id){
    //        if(id == 'button') {//增加操作按钮
    //            var _button = '<button type="button" class="btn btn-white btn-xs" onclick="downMarket(' + data.id + ');">解除绑定 </button> ';
    //            return _button;
    //        }
    //        else if(id == 'nameList'){
    //            if(data.nameList && data.nameList.length > 30){
    //                //return data.nameList.slice(0,30) + "..."
    //                return "<span title='"+data.nameList+"'>"+data.nameList.slice(0,30)+"...</span>"
    //            }
    //            else if(data[id] == null || data[id] == ''){
    //                return ""
    //            }
    //            else{
    //                return data.nameList
    //            }
    //        }
    //        else {
    //            if(data[id] == null || data[id] == ''){
    //                return '';
    //            }else{
    //                return data[id];
    //            }
    //        }
    //
    //
    //    }


    $(function(){

        //获取table数据
        $.ajax({
            type:"GET",
            url:"/admin/manager/json",
            dataType:"json",
            async:"true",
            data:{},
            success:function(data) {
                layer.closeAll('loading');
                if (data.total > 0) {
                    //拼接显示数据
                    var rows = data.rows;
                    var temp = "";
                    for (var i in rows) {
                        if (rows[i].id) {
                            temp += "<tr><td width='10%'>" + rows[i].id + "</td>" +
                                    "<td width='25%'>" + rows[i].realName + "</td>" +
                                    "<td>" + rows[i].phone + "</td>" +
                                    "<td>" + rows[i].phone + "</td>" +
                                    "<td>" + rows[i].phone + "</td>" +
                                    "<td>" + rows[i].phone + "</td>" +
                                    "<td width='15%'><button type='button' class='btn btn-white btn-xs' onclick='downMarket("+rows[i].id+");'>解除绑定 </button></td></tr>";
                        }
                    }
                    $("#tbodyId").append(temp);
                } else {
                    $("#selectManager").text();
                    $("#tbodyId").html('<tr align="center"><td colspan="' + $("#myTable").find("th").length + '">暂无绑定代理商</td><tr>');
                }
            }
        })

        $('#reSel').click(function () {
            $('#manager').html('');
            $('#managerId').val('');
        });

        $("#selectManager,#continueSel").click(function(){
            //初始化下拉框
            $("#pageSize").empty();
            var data = $('#myTable').attr('data-pageSize').split(',');
            for(var i=0;i<data.length;i++) {
                var option = $("<option>").text(data[i]).val(data[i]);
                $("#pageSize").append(option);
            }
            //定义查询选择框
            $.jqPaginator('#pagination', {
                totalPages: 100,
                visiblePages: 6,
                currentPage: 1,
                first: '<li class="first"><a href="javascript:void(0);">首页<\/a><\/li>',
                prev: '<li class="prev"><a href="javascript:void(0);">上一页<\/a><\/li>',
                next: '<li class="next"><a href="javascript:void(0);">下一页<\/a><\/li>',
                last: '<li class="last"><a href="javascript:void(0);">末页<\/a><\/li>',
                page: '<li class="page"><a href="javascript:void(0);">{{page}}<\/a><\/li>',
                onPageChange: function (num) {
                    reSearch(num);
                }
            });
        });
    });


    function reSearch(pageNum){
        //选择推荐人
        var $spbox = $(".super-bg");
        var $tbody = $(".super-box table tbody");

        $spbox.show();
        $tbody.html("");
        //加载层
        layer.load(2);
        //获取form表单传入参数
        var jsonData ={};

        jsonData.begin = (pageNum-1) * $('#pageSize').val();
        jsonData.rows = $('#pageSize').val();
        //计算当前页面
        jsonData.pageNum = pageNum;
        jsonData.pageSize = jsonData.rows;

        //搜索赋值
        var $spText = $(".super-tit input.text");
        var key = $spText.attr("name");
        jsonData[key] = $spText.val();

        //获取数据
        $.ajax({
            type:"GET",
            url:"/admin/manager/json",
            dataType:"json",
            async:"true",
            data:jsonData,
            success:function(data){
                layer.closeAll('loading');
                $('#pageCount').html('当前总记录数:' + data.total);//显示记录数
                if(data.total > 0){
                    //计算页数
                    if(data.total%$('#pageSize').val() > 0){
                        var pageCount = (data.total - data.total%$('#pageSize').val())/$('#pageSize').val() + 1;
                    }else{
                        var pageCount = data.total/$('#pageSize').val();
                    }

                    $('#pagination').jqPaginator('option', {
                        currentPage: pageNum, //当前页数
                        totalPages: pageCount //总页数
                    });

                    //拼接显示数据
                    var rows = data.rows;
                    var temp = "";
                    for(var i in rows){
                        if(rows[i].id){
                            temp += "<tr><td width='10%'>"+rows[i].id+"</td>" +
                                    "<td width='25%'>"+rows[i].realName+"</td>" +
                                    "<td width='25%'>"+rows[i].phone+"</td>" +
                                    "<td width='15%' class='identity-add'><input type='checkbox' value=''></td></tr>";
                        }
                    }
                    $tbody.append(temp);
                    ChooseVal();
                }else{
                    $('#pageCount').html('当前总记录数:0');//显示记录数
                    $("#layTable").html('<tr align="center"><td colspan="' + $("#myTable").find("th").length + '">未查询到匹配的数据</td><tr>');
                }

                //设置统计结果
                if(typeof data.curPage != 'undefined'){
                    var cur = data.curPage;
                    for(var o in cur){
                        $("#"+o+"_cur").text(cur[o]);
                    }
                }
                //设置统计结果
                if(typeof data.allPage != 'undefined'){
                    var cur = data.allPage;
                    for(var o in cur){
                        $("#"+o+"_all").text(cur[o]);
                    }
                }
            },
            error:function(){
                console.log("error")
                //关闭加载层
                layer.closeAll('loading');
                $('#pageCount').html('当前总记录数:0');//显示记录数
                $("#layTable").html('<tr align="center"><td colspan="' + $("#myTable").find("th").length + '">未查询到匹配的数据</td><tr>');
            }
        });
        //关闭按钮
        $(".super-box .fa-close").click(function(){
            $spbox.hide();
            $tbody.html("");
            $(".super-tit input.text").val("");//清空搜索
        });
    };

    //选择函数
    var nameVal = $("#manager").html();
    var idVal = $("#managerId").val();
    var spArr = [],spId = [];
    nameVal && (spArr = nameVal.split(","));
    idVal && (spId = idVal.split(","));
    function ChooseVal(){
        var $sptr = $(".super-box table tbody tr");
        var $spbox = $(".super-bg");
        var $tbody = $(".super-box table tbody");
        //删除数组的元素 -- 定义局部方法
        Array.prototype.remove = function(val) {
            var index = this.indexOf(val);
            if (index > -1) {
                this.splice(index, 1);
            }
        };
        //判断复选框状态 -- id值是否在spId中
        $sptr.each(function(){
            var realId = $(this).find("td").eq(0).text();
            if(spId.indexOf(realId) != "-1"){
                $(this).find("td:last input").attr("checked","checked");
            }
        })

        $sptr.find("td:last input").change(function(){
            //var curTds = $(this).parent().parent().find("td");
            var curVal = $(this).parent().parent().find("td").eq(1).text();
            var curId = $(this).parent().parent().find("td").eq(0).text();
            if($(this).is(":checked") && (spId.indexOf(curId) == -1)){
                spArr.push(curVal);
                spId.push(curId);
            }
            else{
                spArr.remove(curVal);//删除数组的一个元素
                spId.remove(curId);
            }
        });

        $(".super-tit .btn-success").click(function(){
            var $vals = spArr.join(",");
            var $ids = spId.join(",");
            $("#manager").html($vals).siblings("input[name='managerId']").val($ids).change();
            $("#managerDiv input[name='managerId']").val($vals)
            $spbox.hide();
            $tbody.html("");
            $(".super-tit input.text").val("");
            if($('#managerId').val() == ""){
                $('#selectManager').show();
            }else{
                $('#selectManager').hide();
            }
        });
        //console.log(spId)
    };
    var action="add";
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    function closePage() {
        parent.layer.close(index);
    }

    function submitForm() {
        var bsVal = $("#Form").data('bootstrapValidator');
        bsVal.validate();
        if(bsVal.isValid()) {
            //收益边界多选值处理
            var obj=document.getElementsByName('income');
            var income = '';
            for(var i=0; i<obj.length; i++){
                //关闭窗口并刷新页面
                if(obj[i].checked) income+= ','+obj[i].value;
            }
            if(income!=''){
                income = income.substring(1,obj.length-1);
            }
            var manager = $("#managerId").val();

            $.ajax({
                url: '/admin/identity/' + action,
                dataType: 'json',
                type: 'POST',
                data: $("#myForm").serialize() + "&manager=" + manager,
                success: function (data) {
                    if (data.code == '0000' || data.code == '0') {
                        layer.open({
                            type: 1,
                            title: false,
                            content: $(".good-add-suc"),
                            area: ['600px', '400px'],
                            time: 5000,
                            end: function () {
                                parent.layer.closeAll();
                                window.location.href = '/admin/identity';
                            }
                        });
                    } else {
                        layer.alert(data.desc, {
                            icon: 56
                        });
                    }
                },
                error: function () {
                    layer.alert('系统错误', {
                        icon: 5
                    });
                }
            });
        }
        else{
            var smallTop = $("small:visible").eq(0).offset().top - 50;
            $("html,body").animate({scrollTop:smallTop},300);
        }
    }


    function submitForm1() {
//		var $val = $("#setPrice").val();
//		if($val == "" || !regPrice.test($val)){
//			$("#setPrice").siblings("small").show().css("color","#a94442");
//		}
        //	else{
        var bsVal = $("#Form").data('bootstrapValidator');
        bsVal.validate();
        if (bsVal.isValid()) {
            $.ajax({
                method: 'POST',
                dataType: 'json',
                url: '/campsitePosition/setSchedule',
                data: {
                    id:[234,456,654]
//                    campsiteId: $('#campsiteId').val(),
//                    type: $("#type").val(),
//                    date: $("#date").val(),
//                    setPrice: $("#setPrice").val(),
//                    flag:"1"
                },
                success: function (data) {
                    if ("" != data) {
                        var a = "";
                        for (var i = 0; i < data.length; i++) {
                            a = data[i] + "," + a;
                        }
                        $("#positionIds").val(a);
                    }
                    window.location.reload();
                }
            });
        }
    }


    //解除绑定
    function downMarket(id){
        layer.confirm('是否确定此操作？', {
            btn: ['确定','取消'] //按钮
        }, function() {
            $.ajax({
                type: 'POST',
                url: '${basePath}/admin/product/classify/remove?id=' + id,
                success: function (data) {
                    var data = JSON.parse(data);
                    layer.alert('解除成功!', {
                        icon: 6
                    }, function(index){
                        layer.closeAll('dialog');
                        search(parseInt($('.active').attr('jp-data')));
                    });
                }
            });
        });
    }

    //批量解除
    function batchDown(){
        var chk_value =[];
        $("#tbodyId").find("input").each(function() {
            if($(this).attr('type') == 'checkbox' && $(this).is(':checked')){
                chk_value.push($(this).val());
            }
        });
        if(chk_value.join(",") == null || chk_value.join(",") == ''){
            layer.alert('请选择需要解除的内容', {icon : 5});
            return;
        }
        layer.confirm('是否确定此操作？', {
            btn: ['确定','取消'] //按钮
        }, function() {
            $.ajax({
                type: 'POST',
                url: '${basePath}/admin/product/classify/removeList?ids=' + chk_value,
                success: function (data) {
                    var data = JSON.parse(data);
                    if (data.code == '0') {
                        layer.alert('批量解除成功!', {
                            icon: 6
                        }, function(index){
                            layer.closeAll('dialog');
                            search(parseInt($('.active').attr('jp-data')));
                        });
                    } else {
                        layer.alert(data.desc, {
                            icon: 56
                        });
                    }
                }
            });
        });
    }
</script>
</body>
</html>